import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { useRef, useState, useEffect } from 'react'
import { todoDel, updateTodoStatus } from '../store/actions/todo'
export default function TodoItem({ item }) {
  const inputRef = useRef()
  const dispatch = useDispatch()
  const [editId, setEditId] = useState('')
  const handleDelete = (id) => dispatch(todoDel(id))
  const handleUpdateTodoStatus = (id) => dispatch(updateTodoStatus(id))
  // 双击显示编辑框
  const handleDblClick = (id) => {
    setEditId(id)
    // inputRef.current => DOM
  }
  useEffect(() => {
    if (editId === '') return
    inputRef.current.focus()
  }, [editId])
  return (
    <li
      className={classNames({
        completed: item.done,
        editing: editId === item.id,
      })}
    >
      <div className='view'>
        <input
          className='toggle'
          type='checkbox'
          checked={item.done}
          onChange={() => handleUpdateTodoStatus(item.id)}
        />
        <label onDoubleClick={() => handleDblClick(item.id)}>{item.name}</label>
        <button
          className='destroy'
          onClick={() => handleDelete(item.id)}
        ></button>
      </div>
      {/* 做编辑用的 */}
      <input
        className='edit'
        value='Create a TodoMVC template'
        onChange={() => {}}
        ref={inputRef}
      />
    </li>
  )
}
